package com.gin.kotlin.no_gay_alliance.adapter.community

import android.content.Context
import android.view.View
import android.view.ViewGroup
import android.view.ViewGroup.MarginLayoutParams
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions
import com.gin.kotlin.no_gay_alliance.R
import com.gin.kotlin.no_gay_alliance.base.AbstractBindingRecyclerViewAdapter
import com.gin.kotlin.no_gay_alliance.base.GlideModule.Companion.CROSS_FADE
import com.gin.kotlin.no_gay_alliance.base.MyHandler
import com.gin.kotlin.no_gay_alliance.base.TextViewTarget
import com.gin.kotlin.no_gay_alliance.databinding.ItemForumEntryBinding
import com.gin.kotlin.no_gay_alliance.fragment.topiclist.ColListFragment
import com.gin.kotlin.no_gay_alliance.fragment.topiclist.ForumListFragment
import com.gin.kotlin.no_gay_alliance.model.ForumEntryModel
import com.gin.nga.enums.ForumType

/**
 * 版面入口适配器
 * @constructor
 */
class ForumEntryAdapter(
    context: Context,
    handler: MyHandler,
    data: MutableList<ForumEntryModel> = mutableListOf()
) :
    AbstractBindingRecyclerViewAdapter<ItemForumEntryBinding, ForumEntryModel>(context, handler, false, data), View.OnClickListener {
    /**
     * 当显示某一位置的item时的操作
     * @param holder ViewHolder
     * @param position Int
     * @param b ViewBinding
     * @param dataModel 数据对象
     */
    override fun onBindViewHolder(holder: ViewHolder<ItemForumEntryBinding>, position: Int, b: ItemForumEntryBinding, dataModel: ForumEntryModel) {
        val tv = b.root

        tv.text = dataModel.name
        // 点击事件
        tv.setOnClickListener(this)
        // 放入tag
        tv.tag = dataModel

        // 图标大小（dp）
        val size = (48 * context.resources.displayMetrics.density).toInt()

        // 加载版面头像
        Glide.with(context)
            .load(dataModel.icon)
            .error(R.drawable.ic_forum_avatar)
            .placeholder(R.drawable.ic_forum_avatar)
            .transition(DrawableTransitionOptions.withCrossFade(CROSS_FADE))
            .into(TextViewTarget(tv, 1, size, size))
    }

    /**
     * 配置 LayoutParams
     * @param layoutParams LayoutParams
     */
    override fun configLayoutParams(layoutParams: ViewGroup.LayoutParams) = MarginLayoutParams(layoutParams).also { it.topMargin = 50 }

    /**
     * 点击入口的事件
     */
    override fun onClick(v: View?) {
        (v?.tag as? ForumEntryModel)?.also {

            if (it.type == ForumType.FORUM) {
                // 打开版面
                ForumListFragment.startActivity(context, forumId = it.entryId, title = it.name)
            } else {
                // 打开合集
                ColListFragment.startActivity(context, it.entryId, title = it.name)
            }

        }
    }
}